<template>
  <div>
    <el-upload
      :action="url"
      list-type="picture-card"
      :auto-upload="true"
      multiple
      show-file-list
      accept="image/jpeg,image/gif,image/png,image/ipg"
      :limit="10"
      :on-exceed="handleExceed"
      :on-error="uploadError"
      :on-success="uploadSuccess"
      :before-upload="onBeforeUpload"
      :on-preview="handlePictureCardPreview"
      ref="upload"
      :headers="headerObj"
    >
      <i slot="default" class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import store from "@/store";
var storeTemp = store;
// console.log(storeTemp.state.token);
export default {
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      token:storeTemp.state.token,
      headerObj:{
        "Authorization":"Bearer "+storeTemp.state.token
      }
    };
  },
  props:["url"],
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      // console.log(file);
      var a=document.createElement('a');
      var event=new MouseEvent('click');
      a.download=file.name;
      a.href=file.url;
      a.dispatchEvent(event);
    },
    handleExceed(file,fileList){
      this.$message.warning("最多只能同时上传10个");
    },
    uploadError(err, file, fileList){
      this.$message.error("上传失败")
    },
    uploadSuccess(response, file, fileList){
      this.$message.success("上传成功");
      // console.log(response);
      var data=response.response;//以数组计算，因为上传多个时是返回的数组
      // 解析从后台返回的数据，并将数据传回父组件
      this.$emit("uploadSuccess",data);
    },
    onBeforeUpload(file){
      //上传之前对file进行校验
      const isIMAGE = file.type === 'image/jpeg'||'image/gif'||'image/png'||'image/jpg';
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!');
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!');
      }
      return isIMAGE && isLt1M;
    },
    clearFiles(){
      // console.log("clear");
      this.$refs.upload.clearFiles();
    }
  },
};
</script>